import React,{useState,useEffect,useRef} from "react"
import { Button, Card , Form ,Table , Input ,Modal,notification,message} from 'antd'
import { PlusOutlined ,SearchOutlined ,DeleteOutlined,ExclamationCircleOutlined} from '@ant-design/icons'
import { getToken ,addKeyFn} from '../../utils/utils'
import axios from 'axios'

function ActivityType(){
    const [tableData,setTableData] = useState([])
    useEffect(()=>{
        axios.get('/my/type/cates',{
            headers:{
                'Authorization':getToken()
            }
        }).then(res=>{
            const result = JSON.stringify(res.data.data)
            setTableData(addKeyFn(JSON.parse(result)))
        })
    },[])

    const [isShow,setIsShow] = useState(false)
    const [myForm] = Form.useForm()
    const addForm = useRef(null)

     // 删除操作
     const deleMethod =(item)=>{
        // 当前页面同步状态
        setTableData(tableData.filter(data=>data.typeId !== item.typeId))
        const typeId = item.typeId
        console.log(item)
        //要前后端同步
        axios.get('/my/type/deletecate/'+typeId,{
            headers:{'Authorization':getToken()}
        })
    }
    const confirmMethod=(item)=>{
        Modal.confirm({
            title: '您确定要删除吗?',
            icon: <ExclamationCircleOutlined />,
            onOk() {
                console.log('ok')
                deleMethod(item);
                notification.info({
                message:'通知',
                description:'删除成功',
                placement:"bottomRight",
                });
            },
            onCancel() {
                console.log('Cancel');
            },
        });
    }
    // 添加活动
    const addFormOk=()=>{
        addForm.current.validateFields().then(value=>{
            // console.log(value.activityTitle)
            setIsShow(false)
            //从post到后端生成ID，方便删除和更新，自增长id
            axios({
                method:'post',
                url:'/my/type/addcates',
                headers:{
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Authorization':getToken()
                },
                data:{...value}
               
            }).then(res=>{
              notification.info({
                message:'通知',
                description:res.data.message,
                placement:"bottomRight",
              });
            })
          }).catch(err=>{
            console.log(err)
          })
    }


      // 查询
      const [myform] = Form.useForm()
      // 搜索按钮事件
      const searchBtn = obj=>{
          console.log(obj)
          myform.setFieldsValue({typeName:''})
          if(obj.typeName === undefined){
              message.success('请输入活动标题')
              return false
          }
          setTableData(tableData.filter(data=>data.typeName == obj.typeName))
          const typeName = obj.typeName
          // console.log(item)
          axios.get('/my/type/cates/'+typeName,{
              headers:{'Authorization':getToken()}
          })
  
      }


    const columns = [
        {
            title:'类型序号',
            key:'key',
            dataIndex:'key',
            render:(key)=>{
                return <b>{key}</b>
            }
            
        },{
            title:'名称',
            key:'typeName',
            dataIndex:'typeName',
            render:(typeName)=>{
                return <b>{typeName}</b>
            }
        },{
            title:'别名',
            key:'typeAlias',
            dataIndex:'typeAlias',
            render:(typeAlias)=>{
                return <b>{typeAlias}</b>
            }
        },{
            title:'操作',
            key:'action',
            render:(item)=>{
                return <div>
                  <Button danger shape="circle" 
                    icon={<DeleteOutlined />}  
                    style={{marginRight:"10px"}}
                    onClick={()=>confirmMethod(item)}
                  />
                </div>
              }
        }
    ]
    return (
        <div>
            <Card
                title="类型列表"
                extra={
                    <div>
                        <Button type="primary" 
                            icon={<PlusOutlined/>}
                            onClick={()=>{setIsShow(true)}}
                            style={{opacity:0.9,backgroundColor:"Highlight"}}
                        >添加活动类型</Button>
                    </div>
                }  
            >
                <Form 
                layout="inline"
                form={myform}
                onFinish={(n)=>{
                    // console.log(n)
                    searchBtn(n)
                }}
                >
                    <Form.Item label='类型名称' name='typeName'>
                        <Input placeholder="请输入要查询的类型名称"/>
                    </Form.Item>
                    <Button htmlType="submit" type="primary" icon={<SearchOutlined />}></Button>  
                </Form>
                <Table 
                    // text-align='center'
                    dataSource={tableData}
                    columns={columns}
                    pagination={{pageSize:3}} 
                    rowKey={record=>record.typeId}
                    >
                </Table>
            </Card>
            <Modal
                title="编辑输入框"
                open={isShow}
                maskClosable={false}
                onCancel={()=> setIsShow(false)}
                onOk={()=>{
                //   myForm.submit();
                addFormOk()
                }}
            >
                <Form
                    ref={addForm}
                    form={myForm}
                    labelCol={{span:4}}
                    onFinish={(n)=>{
                        message.success('添加成功')
                    }}
                >
                    <Form.Item label='类型名称' name='typeName' rules={[{required:true,message:'请输入活动类型名称'}]}>
                        <Input placeholder="请输入活动类型名称" />
                    </Form.Item>
                    
                    <Form.Item label='类型别名' name='typeAlias' rules={[{required:true,message:'请输入活动类型别名'}]}>
                        <Input placeholder="请输入活动类型别名" />
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    )
}
export default ActivityType